package com.im.app.controller;


import com.im.app.authConfig.CurrentUser;
import com.im.app.authConfig.RequireLogin;
import com.im.app.model.User;
import com.im.app.service.IGroupMemberService;
import com.im.app.service.IGroupService;
import com.im.app.utils.Response;
import com.im.app.utils.ResponseResult;
import com.im.app.utils.uuid.IdUtils;
import org.jim.core.ImChannelContext;
import org.jim.core.ImPacket;
import org.jim.core.packets.*;
import org.jim.core.utils.JsonKit;
import org.jim.server.JimServerAPI;
import org.jim.server.util.ChatKit;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 群组成员控制器
 */
@RestController
@RequestMapping(value = "/groupMember")
public class IMGroupMemberController {

    @Resource
    private IGroupService groupService;
    @Resource
    private IGroupMemberService groupMemberService;

    /**
     * 获取当前群组成员
     * @param groupId
     * @return
     */
    @RequireLogin
    @GetMapping("/getGroupMemberList")
    public ResponseResult<Object> getGroupMemberList(String groupId){
        List<GroupMember> groupMembers = groupMemberService.selectGroupMemberByGroupId(groupId);
        return Response.makeOKRsp().setData(groupMembers);
    }


    /**
     * 查看群成员信息(groupId、userId)
     * @param groupMember
     * @return
     */
    @RequireLogin
    @GetMapping("/getGroupMember")
    public ResponseResult<Object> getGroupMember( GroupMember groupMember){
        if(null == groupMember){
            Response.makeErrRsp("参数异常");
        }
        List<GroupMember> groupMembers = groupMemberService.selectGroupMemberList(groupMember);
        if(groupMembers!=null){
            return Response.makeOKRsp().setData(groupMembers.get(0));
        }
        return Response.makeErrRsp("无该成员");
    }

    /**
     * 添加群成员
     * @return
     */
    @RequireLogin
    @PostMapping("/addGroupMember")
    public ResponseResult<Object> addGroupMember(@CurrentUser User user,@RequestBody List<GroupMember> groupMembers){
        String groupId = "";
        if (groupMembers.size() > 0){
            groupId = groupMembers.get(0).getGroupId();
        }

        Group group = groupService.selectGroupsByGroupId(groupId);
        if (group == null){
            return Response.makeErrRsp("没有对应群信息");
        }
        if(isPublicRole(user.getUserId(),groupId)){
            return Response.makeErrRsp("该账号没有操作权限");
        }
        StringBuilder message = new StringBuilder("管理员邀请了用户 ");
        int i = 0;
        List<GroupMember> groupMemberList = new ArrayList<>();
        for (GroupMember groupMember : groupMembers){
            GroupMember groupMember1 = groupMemberService.selectGroupMember(groupId, groupMember.getUserId());
            if (groupMember1 == null){
                groupMember.setJoinTime(new Date());
                int result = groupMemberService.insertGroupMember(groupMember);
                if (result > 0){
                    message.append(groupMember.getNickname());
                    if (i < groupMembers.size() - 1){
                        message.append(",");
                    }
                    groupMemberList.add(groupMember);
                    JimServerAPI.bindGroup(groupMember.getUserId(),groupId); //绑定群成员
                    ChatBody chatMessage = new ChatBody();
                    chatMessage.setId(IdUtils.simpleUUID());
                    chatMessage.setNickName(user.getName());
                    chatMessage.setAvatar(user.getAvatar());
                    chatMessage.setContent(JsonKit.toJSONString(group));
                    chatMessage.setMsgType(MsgType.MSG_JOIN_GROUP.getNumber());
                    chatMessage.setFromType(1);
                    chatMessage.setFrom(user.getUserId());
                    chatMessage.setCmd(Command.COMMAND_CHAT_REQ.getNumber());
                    chatMessage.setTo(groupMember.getUserId());
                    chatMessage.setChatType(ChatType.CHAT_TYPE_PRIVATE.getNumber());
                    chatMessage.setCreateTime(new Date().getTime());
                    JimServerAPI.sendUserMessage(chatMessage,user.getUserId());
                }
            }
        }
        ChatBody chatBody = group.updateMessageTip(message.toString());
        JimServerAPI.sendGroupMessage(chatBody,user.getUserId()); //发送成员进入提示消息
        ImPacket imPacket  = new ImPacket(Command.COMMAND_JOIN_GROUP_NOTIFY_RESP,new RespBody(Command.COMMAND_JOIN_GROUP_NOTIFY_RESP,groupMemberList).toByte());
        JimServerAPI.sendToGroup(groupId,imPacket); //发送进入成员列表

        if(groupMemberList.size()>0){
            return Response.makeOKRsp(groupMemberList);
        }
        return Response.makeErrRsp("操作失败");
    }

    /**
     * 修改群成员信息（状态）
     * @param groupMember
     * @return
     */
    @RequireLogin
    @PostMapping("/updateGroupMember")
    public ResponseResult<Object> updateGroupMember(@CurrentUser User user,@RequestBody GroupMember groupMember){
        if(null == groupMember){
            return Response.makeErrRsp("参数异常");
        }
        if(isPublicRole(user.getUserId(),groupMember.getGroupId())){
            return Response.makeErrRsp("该账号没有操作权限");
        }
        int result = groupMemberService.updateGroupMember(groupMember);
        //修改通知。。。。

        if(result>0){
            return Response.makeOKRsp("操作成功");
        }
        return Response.makeErrRsp("操作失败");
    }

    @RequireLogin
    @PostMapping("/updateGroupMemberRole")
    public ResponseResult<Object> updateGroupMemberRole(@CurrentUser User user,@RequestBody GroupMember groupMember){
        if(null == groupMember){
            return Response.makeErrRsp("参数异常");
        }
        if (groupMember.getGroupId() == null){
            return Response.makeErrRsp("群ID不能为空");
        }
        Group group = groupService.selectGroupsByGroupId(groupMember.getGroupId());
        if (group == null){
            return Response.makeErrRsp("没有对应群信息");
        }

        if (groupMember.getUserId() == null){
            return Response.makeErrRsp("群成员ID不能为空");
        }

        if(isPublicRole(user.getUserId(),groupMember.getGroupId())){
            return Response.makeErrRsp("该账号没有操作权限");
        }


        GroupMember groupMember1 = groupMemberService.selectGroupMember(groupMember.getGroupId(), groupMember.getUserId());
        if (groupMember1 == null){
            return Response.makeErrRsp("没有应对群成员信息");
        }

        groupMember1.setRole(groupMember.getRole());
        int result = groupMemberService.updateGroupMember(groupMember1);

        if(result>0){
            ImPacket imPacket  = new ImPacket(Command.COMMAND_GROUP_MEMBER_INFO_NOTIFY_RESP,new RespBody(Command.COMMAND_GROUP_MEMBER_INFO_NOTIFY_RESP,groupMember1).toByte());
            JimServerAPI.sendToGroup(group.getGroupId(),imPacket);
            return Response.makeOKRsp("操作成功");
        }
        return Response.makeErrRsp("操作失败");
    }


    /**
     * 删除群成员（状态）
     * @param groupMember
     * @return
     */
    @RequireLogin
    @GetMapping("/deleteGroupMember")
    public ResponseResult<Object> deleteGroupMember(@CurrentUser User user,@RequestBody GroupMember groupMember){
        if(null == groupMember){
            return Response.makeErrRsp("参数异常");
        }
        if (groupMember.getGroupId() == null){
            return Response.makeErrRsp("群ID不能为空");
        }
        if(isPublicRole(user.getUserId(),groupMember.getGroupId())){
            return Response.makeErrRsp("该账号没有操作权限");
        }
        if(groupMember.getRole() != GroupMemberType.ROLE_PUBLIC.getNumber()){
            return Response.makeErrRsp("请重新选择删除角色");
        }
        int result = groupMemberService.deleteGroupMemberByUserId(groupMember.getUserId());
        //清空该成员会话。。。。。
        //删除通知。。。。

        if(result>0){
            return Response.makeOKRsp("操作成功");
        }
        return Response.makeErrRsp("操作失败");
    }

    public boolean isPublicRole(String userId,String groupId){
        List<GroupMember> groupMembers = groupMemberService.selectGroupMemberByGroupId(groupId);
        for (GroupMember member : groupMembers) {
            //判断当前用户是否为群主或者管理员
            if(userId.equals(member.getUserId())){
                if(member.getRole() == GroupMemberType.ROLE_PUBLIC.getNumber()){
                   return true;
                }
            }
        }
        return false;
    }


}
